package com.dyh.quickdemo.demos.autoBean;


import com.dyh.quickdemo.demos.autoBean.example.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/*

*/
@Slf4j
public class SpringRegist implements ApplicationListener<ApplicationReadyEvent> {

//    public Class targetCls = Enhance.class;
    /*bean 的初始化都完成了*/
    @Override
    public void onApplicationEvent(ApplicationReadyEvent are) {
        ApplicationContext ac = are.getApplicationContext();

        BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(Example.class);


        DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) ac.getAutowireCapableBeanFactory();

        String registerBeanName = Example.class.getSimpleName()+"Impl";
        dlbf.registerBeanDefinition(registerBeanName, bdb.getBeanDefinition());

    }
    /*
      ApplicationContext ac = are.getApplicationContext();
        Map<String, Object> name2Bean = ac.getBeansWithAnnotation( Enhance.class);
        if (CollectionUtils.isEmpty(name2Bean))
            return;
        for (String beanName:name2Bean.keySet()){

             Object bean = name2Bean.get(beanName);
//            if (!(bean instanceof Job))
//                continue;
             Class<?> beanClass = bean.getClass();
             log.info("beanClass="+beanClass);
             Enhance jobAnno = beanClass.getAnnotation( Enhance.class);//上面加个? 这里就不用强转了



            BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(beanClass);


            DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) ac.getAutowireCapableBeanFactory();

            String registerBeanName = jobAnno.code() + beanClass.getSimpleName();
            dlbf.registerBeanDefinition(registerBeanName, bdb.getBeanDefinition());
    */
}
